<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>

<body>
    <h2>设置cookie</h2>
    <a href="http://sluggish.gitee.io/staticpages/tab-communication/cookies/other.html" target="_blank">打开另一个页面</a><br>
    <label>key:
        <input type="text" class="key">
    </label>
    <label>value:
        <input type="text" class="value">
    </label>
    <label>expires:
        <input type="text" class="expires" placeholder="距离过期还有几天">
    </label>
    <button class="submit-cookie">确定</button>
    <h2>获取cookie</h2>
    <button class="get-cookies">获取cookie</button>
    <div class="cookie-content"></div>
    <script type="text/javascript" src="../../source/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
    var CookieUtil = {
        get: function(name) {
            var cookieName = encodeURIComponent(name) + '=',
                cookieStart = document.cookie.indexOf(cookieName),
                cookieValue = null;
            if (cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf(';', cookieStart);
                if (cookieEnd == -1) {
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
            }
            return cookieValue;
        },

        // expires传入的是过期那个日期 或者 距离过期的天数
        set: function(name, value, expires, path, domain, secure) {
            var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value),
                exp;

            if (expires instanceof Date) { // 具体日期
                cookieText += '; expires=' + expires.toUTCString();
            } else if (typeof expires === 'number') { // 过期天数
                exp = new Date();
                exp.setTime(exp.getTime() + expires * 1000 * 3600 * 24);
                cookieText += '; expires=' + exp.toUTCString();
            }

            if (path) {
                cookieText += '; path=' + path;
            }
            if (domain) {
                cookieText += '; domain=' + domain;
            }
            if (secure) {
                cookieText += '; secure';
            }
            document.cookie = cookieText;
        },

        remove: function(name, path, domain, secure) {
            this.set(name, '', new Date(0), path, domain, secure);
        }
    };

    var $key = $('.key'),
        $value = $('.value'),
        $expires = $('.expires'),
        $cookieContent = $('.cookie-content');
    $('.submit-cookie').on('click', function() {
        CookieUtil.set($key.val(), $value.val(), parseInt($expires.val().trim()));
    });
    $('.get-cookies').on('click', function() {
        $cookieContent.text(document.cookie);
    });
    </script>
</body>

</html>